package com.example.mqtt.paho.mqtt.consumer;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Component;


/**
 * @author long
 */
@Component
public class MqttConsumer {

    private static final Logger logger = LoggerFactory.getLogger(MqttConsumer.class);

    @Bean
    @ServiceActivator(inputChannel = "mqttInputChannel")
    MessageHandler messageHandler() {
        return new MessageHandler() {
            @Override
            public void handleMessage(Message<?> message) throws MessagingException {
                logger.info("接收消息报文[{}]", JSON.toJSONString(message));
                //获取消息来自哪个topic
                String topic = (String) message.getHeaders().get("mqtt_receivedTopic");
                logger.error("接收消息主题[{}]", topic);
                //获取消息内容 原始数据为byte[]格式 需要转为String
                String msg = new String((byte[]) message.getPayload());
                logger.error("接收消息内容[{}]", msg);
            }
        };
    }


}
